package com.hzncc.flowable_diboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.service.impl.BaseServiceImpl;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.S;
import com.diboot.core.vo.JsonResult;
import com.diboot.iam.util.IamSecurityUtils;
import com.diboot.notification.config.Cons;
import com.diboot.notification.entity.Message;
import com.hzncc.flowable_diboot.entity.Business;
import com.hzncc.flowable_diboot.entity.BusinessTeam;
import com.hzncc.flowable_diboot.entity.SalesTeam;
import com.hzncc.flowable_diboot.mapper.BusinessMapper;
import com.hzncc.flowable_diboot.mapper.BusinessTeamMapper;
import com.hzncc.flowable_diboot.rabbitmq.service.impl.SendMessageService;
import com.hzncc.flowable_diboot.service.BusinessTeamService;
import com.hzncc.flowable_diboot.service.SalesTeamService;
import com.hzncc.flowable_diboot.util.ConstantUtil;
import com.hzncc.flowable_diboot.util.MessageCons;
import com.hzncc.flowable_diboot.vo.BusinessTeamListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 商机团队 相关Service实现类
 *
 * @author MyName
 * @version 1.0
 * @date 2024-06-13
 * Copyright © MyCorp
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessTeamServiceImpl extends BaseServiceImpl<BusinessTeamMapper, BusinessTeam> implements BusinessTeamService {

    private final SendMessageService sendMessageService;
    private final BusinessMapper businessMapper;
    private final SalesTeamService salesTeamService;

    @Override
    public JsonResult<?> kickTheTeam(String id) {
        BusinessTeamListVO entity = getViewObject(id, BusinessTeamListVO.class);
        Business business = businessMapper.selectById(entity.getBusinessId());
        if (!S.equals(business.getUid(), IamSecurityUtils.getCurrentUserId())) {
            return JsonResult.FAIL_NO_PERMISSION("权限不足，请联系负责人");
        }
        deleteEntity(id);
        sendMessageService.sendRetainedMessage(new Message().setTemplateId("")
                .setTitle(MessageCons.BUS_TEAM_TITLE)
                .setContent("您已被移出【" + entity.getBusinessIdLabel() + "】团队")
                .setReceiver(entity.getMemberId())
                .setBusinessType("").setBusinessCode("").setAppModule(ConstantUtil.MODEL_SALES)
                .setChannel(Cons.MESSAGE_CHANNEL.SYS_MSG.name())
                .setStatus(Cons.MESSAGE_STATUS.DELIVERY.name())
                .setSender(IamSecurityUtils.getCurrentUserId()));
        return JsonResult.OK();
    }

    @Override
    public JsonResult<?> addMember(List<BusinessTeam> team) {
        // 获取客户
        String businessId = team.get(0).getBusinessId();
        Business bu = businessMapper.selectById(businessId);
        if (!S.equals(bu.getUid(), IamSecurityUtils.getCurrentUserId())) {
            return JsonResult.FAIL_NO_PERMISSION("权限不足，请联系负责人");
        }
        String customerId = bu.getCustomerId();
        // 检查是否重复添加
        List<String> memberIds = BeanUtils.collectToList(team, BusinessTeam::getMemberId);
        // 已存在的商机团队
        QueryWrapper<BusinessTeam> qw = new QueryWrapper<>();
        qw.in("member_id", memberIds);
        qw.eq("business_id", bu.getId());
        List<BusinessTeam> s = getEntityList(qw);
        List<String> existMembers = BeanUtils.collectToList(s, BusinessTeam::getMemberId);
        // 过滤掉重复数据
        if (!existMembers.isEmpty()) {
            team = team.stream().filter(e -> !existMembers.contains(e.getMemberId())).collect(Collectors.toList());
        }
        if (team.isEmpty()) {
            return JsonResult.OK();
        }
        createEntities(team);
        List<String> validMember = BeanUtils.collectToList(team, BusinessTeam::getMemberId);
        // 已存在的销售团队
        QueryWrapper<SalesTeam> wrapper = new QueryWrapper<>();
        wrapper.in("member", validMember);
        wrapper.eq("customer_id", customerId);
        List<SalesTeam> st = salesTeamService.getEntityList(wrapper);
        List<String> existMe = BeanUtils.collectToList(st, SalesTeam::getMember);
        if (!existMe.isEmpty()) {
            team = team.stream().filter(e -> !existMe.contains(e.getMemberId())).collect(Collectors.toList());
        }
        // 将商机团队成员添加到客户销售团队
        List<SalesTeam> salesTeams = new ArrayList<>();
        for (BusinessTeam businessTeam : team) {
            SalesTeam salesTeam = new SalesTeam();
            salesTeam.setMember(businessTeam.getMemberId());
            salesTeam.setRole(businessTeam.getRole());
            salesTeam.setPermissions(businessTeam.getPermissions());
            salesTeam.setCustomerId(customerId);
            salesTeams.add(salesTeam);
        }
        salesTeamService.createEntities(salesTeams);
        return JsonResult.OK();
    }
}